package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpServletResponse {
    private int stausCode=200;
    private String stausReason="OK";
    //响应头相关信息
    //key响应头的名字  value响应头对应的值
    private Map<String,String> headers=new HashMap<>();
    //响应正文相关信息
    private File contentFile;//响应正文对应的文件,该文件会作为正文内容发送
    private Socket socket;
    public HttpServletResponse(Socket socket) {
    this.socket=socket;
    }
    public void response()throws IOException {
        //3.1发送状态行
        sendStatusLine();

        //3.2发送响应头
        sendHeaders();

        //3.3发送响应正文
        sendContent();



        System.out.println("响应发送完毕!");

    }
    //1.1解析请求行
   private void sendStatusLine() throws IOException {
       //3.1发送状态行
       String line="HTTP/1.1"+" "+stausCode+" "+stausReason;
       println(line);
   }
    //1.2解析消息头
    private void sendHeaders() throws IOException {
        //3.2发送响应头

        Set<Map.Entry<String,String>> headerSet=headers.entrySet();
        for (Map.Entry<String,String> e:headerSet){
            String key=e.getKey();
            String value=e.getValue();
            println(key+": "+value);
        }
        println("");
    }
    //1.3解析请求行
    private void sendContent() throws IOException {
        //3.3发送响应正文
        OutputStream out=socket.getOutputStream();
      try (
              FileInputStream fis=new FileInputStream(contentFile);
        ){
        byte[] data=new byte[1024*10];
        int len;
        while ((len=fis.read(data))!=-1){
            out.write(data,0,len);
        }
      }
    }
    private void println(String line) throws IOException {
        OutputStream out=socket.getOutputStream();
        byte[]data=line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);//单独发送回车符
        out.write(10);//单独发送换行符
    }

    public int getStausCode() {
        return stausCode;
    }

    public void setStausCode(int stausCode) {
        this.stausCode = stausCode;
    }

    public String getStausReason() {
        return stausReason;
    }

    public void setStausReason(String stausReason) {
        this.stausReason = stausReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }

    //添加一对响应头
    public void addHeader(String name,String value){
        this.headers.put(name,value);
    }
}
